package com.ruoyi.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.business.domain.FilePerson;
import com.ruoyi.business.domain.FilePersonAssess;
import com.ruoyi.business.domain.bo.FilePersonAssessBo;
import com.ruoyi.business.domain.vo.FilePersonAssessVo;
import com.ruoyi.business.mapper.FilePersonAssessMapper;
import com.ruoyi.business.mapper.FilePersonMapper;
import com.ruoyi.business.service.IFilePersonAssessService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.page.TableDataInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 人员考核Service业务层处理
 *
 * @author sal
 * @date 2024-11-26
 */
@RequiredArgsConstructor
@Service
public class FilePersonAssessServiceImpl implements IFilePersonAssessService {

    private final FilePersonAssessMapper baseMapper;
    @Autowired
    private FilePersonMapper filePersonMapper;

    /**
     * 查询人员考核
     */
    @Override
    public FilePersonAssessVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询人员考核列表
     */
    @Override
    public TableDataInfo<FilePersonAssessVo> queryPageList(FilePersonAssessBo bo, PageQuery pageQuery) {
        MPJLambdaWrapper<FilePersonAssess> lqw = buildQueryWrapper(bo);
        Page<FilePersonAssessVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询人员考核列表
     */
    @Override
    public List<FilePersonAssessVo> queryList(FilePersonAssessBo bo) {
        MPJLambdaWrapper<FilePersonAssess> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private MPJLambdaWrapper<FilePersonAssess> buildQueryWrapper(FilePersonAssessBo bo) {
        MPJLambdaWrapper<FilePersonAssess> lqw = new MPJLambdaWrapper<FilePersonAssess>();
        lqw.selectAll(FilePersonAssess.class)
            .selectAs(FilePerson::getName,FilePersonAssess::getPersonName)
            .selectAs(SysDept::getDeptName,FilePersonAssess::getFirmName)
            .leftJoin(FilePerson.class, FilePerson::getId, FilePersonAssess::getPersonId)
            .leftJoin(SysDept.class,SysDept::getDeptId, FilePersonAssess::getFirm)
            .like(StrUtil.isNotBlank(bo.getPersonName()), FilePerson::getName, bo.getPersonName())
            .like(StrUtil.isNotBlank(bo.getAssessYear()), FilePersonAssess::getAssessYear, bo.getAssessYear());
        return lqw;
    }

    /**
     * 新增人员考核
     */
    @Override
    public Boolean insertByBo(FilePersonAssessBo bo) {
        FilePersonAssess add = BeanUtil.toBean(bo, FilePersonAssess.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改人员考核
     */
    @Override
    public Boolean updateByBo(FilePersonAssessBo bo) {
        FilePersonAssess update = BeanUtil.toBean(bo, FilePersonAssess.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(FilePersonAssess entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除人员考核
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void importData(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        EasyExcel.read(inputStream, new AnalysisEventListener<Map<Integer, String>>() {
            @Override
            public void invoke(Map<Integer, String> data, AnalysisContext context) {
                // 处理每一行的数据
                String code = data.get(2); //编号
                String result = data.get(28); //考核结果（2023年度）
                String result2 = data.get(42); //考核结果（2022年度）
                String result3 = data.get(43); //考核结果（2021年度）
                String result4 = data.get(44); //考核结果（2020年度）
                QueryWrapper<FilePerson> personQueryWrapper = new QueryWrapper<FilePerson>().eq("code", code);
                FilePerson filePerson = filePersonMapper.selectOne(personQueryWrapper);
                if ( filePerson == null) {
                    //这里应该返回一个消息提醒，人员不存在
                }else {
                    //人员存在，判断一下该年度考核成绩是否录入
                    FilePersonAssessBo filePersonAssessBo = new FilePersonAssessBo();
                    filePersonAssessBo.setPersonId(filePerson.getId());
                    filePersonAssessBo.setAssessYear(String.valueOf(2023));
                    List<FilePersonAssessVo> list = queryList(filePersonAssessBo);
                    if(list.size() == 0){
                        filePersonAssessBo.setAssessResults(result);
                        insertByBo(filePersonAssessBo);
                    }else{
                        filePersonAssessBo.setId(list.get(0).getId());
                        filePersonAssessBo.setAssessResults(result);
                        updateByBo(filePersonAssessBo);
                    }

                    //人员存在，判断一下该年度考核成绩是否录入
                    FilePersonAssessBo filePersonAssessBo2 = new FilePersonAssessBo();
                    filePersonAssessBo2.setPersonId(filePerson.getId());
                    filePersonAssessBo2.setAssessYear(String.valueOf(2022));
                    List<FilePersonAssessVo> list2 = queryList(filePersonAssessBo2);
                    if(list2.size() == 0){
                        filePersonAssessBo2.setAssessResults(result2);
                        insertByBo(filePersonAssessBo2);
                    }else{
                        filePersonAssessBo2.setId(list2.get(0).getId());
                        filePersonAssessBo2.setAssessResults(result2);
                        updateByBo(filePersonAssessBo2);
                    }

                    //人员存在，判断一下该年度考核成绩是否录入
                    FilePersonAssessBo filePersonAssessBo3 = new FilePersonAssessBo();
                    filePersonAssessBo3.setPersonId(filePerson.getId());
                    filePersonAssessBo3.setAssessYear(String.valueOf(2021));
                    List<FilePersonAssessVo> list3 = queryList(filePersonAssessBo3);
                    if(list3.size() == 0){
                        filePersonAssessBo3.setAssessResults(result3);
                        insertByBo(filePersonAssessBo3);
                    }else{
                        filePersonAssessBo3.setId(list3.get(0).getId());
                        filePersonAssessBo3.setAssessResults(result3);
                        updateByBo(filePersonAssessBo3);
                    }

                    //人员存在，判断一下该年度考核成绩是否录入
                    FilePersonAssessBo filePersonAssessBo4 = new FilePersonAssessBo();
                    filePersonAssessBo4.setPersonId(filePerson.getId());
                    filePersonAssessBo4.setAssessYear(String.valueOf(2020));
                    List<FilePersonAssessVo> list4 = queryList(filePersonAssessBo4);
                    if(list4.size() == 0){
                        filePersonAssessBo4.setAssessResults(result4);
                        insertByBo(filePersonAssessBo4);
                    }else{
                        filePersonAssessBo4.setId(list4.get(0).getId());
                        filePersonAssessBo4.setAssessResults(result4);
                        updateByBo(filePersonAssessBo4);
                    }
                }
            }
            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                System.out.println("All data has been read.");
            }
        }).sheet().headRowNumber(2).doRead();
    }
}
